<script setup>

import {useStore} from "vuex";
import {CircleCheck, Delete, Download, EditPen, Plus, Refresh, Search} from "@element-plus/icons-vue";
import {onBeforeMount, reactive, ref} from 'vue'
import {ElNotification, ElTable} from 'element-plus'
import PageComponent from "@/views/PageComponent.vue";
import http from "@/http";
import table2excel from 'js-table2excel'
import { ElMessage } from 'element-plus'
import { ElTree } from 'element-plus'



const store = useStore();

const  aa = () =>{
  store.state.isCollpace = !store.state.isCollpace
}

const multipleTableRef = ref()
const multipleSelection = ref([])

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const tableData = ref([])

const page = ref(1);
const size = ref(5);
const total = ref(0);
const title = ref("添加角色")

const dialogFormVisible = ref(false)


const handleChange = (value) => {
  console.log(value)
}

onBeforeMount(()=>{
   select(page,size)
})

const role = ref({
  roleId:"",
  roleName:'',
  roleKey:'',
  roleSort:"",
  status:"",
  createTime:"",
  page:page.value,
  size:size.value
})

const role1 = reactive({
  roleId:"",
  roleName:'',
  roleKey:'',
  roleSort:"",
  status:"",
  createTime:"",
  menus:'',
  remark:''
})

const  roles = ref([])

const select = (page,size) =>{
  role.value.page = page
  role.value.size = size
  selectAxios()
}
const selectAxios = ()=>{
  http.post("/LinkRoleGl/getAllrole",role.value).then((res)=>{
    tableData.value = res.data.list
    total.value=res.data.total
  })
}
//导出
const DaoChu = () =>{
  const coulmn = [
    {
      title:"角色编号",
      key:"roleId",
      type:"text"
    },
    {
      title:"角色名称",
      key:"roleName",
      type:"text"
    },
    {
      title:"权限字符",
      key:"roleKey",
      type:"text"
    },
    {
      title:"显示顺序",
      key:"roleSort",
      type:"text"
    },
    {
      title:"状态",
      key:"status",
      type:"text"
    },
    {
      title:"创建时间",
      key:"createTime",
      type:"text"
    }
  ]
  table2excel(coulmn,tableData.value,'数据')
  ElNotification({
    title: '成功',
    message: '导出成功,为excal表格',
    type: 'success',
  })
}

//模糊
const Moh=()=>{
   if (role.value.status == '启用'){
      role.value.status = true
   }else if (role.value.status == "禁用"){
     role.value.status = false
   }else if (role.value.status == '' ){
     role.value.status = ''
   }else {
     role.value.status = ''
     ElMessage({
       message: '请在状态栏输入禁用或者启用',
       type: 'warning',
     })
   }
   select(page.value,size.value)
}

const ChoZ=()=>{
   role.value = {
     roleId:"",
     roleName:"",
     roleKey:"",
     roleSort:"",
     status:"",
     createTime:"",
     page:page.value,
     size:size.value
   }
  ElMessage({
    message: '重置成功',
    type: 'success',
  })
}

//选择框修改
const UpdateRole=()=>{
   console.log(multipleSelection.value)
  if (multipleSelection.value.length>0 && multipleSelection.value.length==1){
       if (data.value.length==0){
          selectMenu()
       }
      Upd1()
  }else if (multipleSelection.value.length >1) {
    ElMessage({
      message: '只能支持修改一个角色',
      type: 'warning',
    })
  }else {
    ElMessage({
      message: '没有选择要修改的角色,请选择一个角色',
      type: 'warning',
    })
  }
}

//表格内修改
const UpdAlag=(scop)=>{
  console.log(scop)
  if (data.value.length==0){
    selectMenu()
  }
  title.value = "修改角色"
  Object.assign(role1,scop)
  selectMenuRole(role1.roleId)
  dialogFormVisible.value  = true
}


const treeRef = ref()

const defaultProps = {
  children: 'chillist',
  label: 'menuName',
}

const data = ref([])
const dataHx = ref([])

const AddDilag=()=>{
      role1.roleId=""
      role1.roleName=''
      role1.roleKey=''
      role1.roleSort=1
      role1.status=""
      role1.menus=''
      role1.remark=''
      dialogFormVisible.value = true
     if(data.value.length==0) {
       selectMenu()
     }else {
       treeRef.value.setCheckedKeys([], false)
     }
}

const selectMenu = ()=>{
  http.post("/LinkRoleGl/selectMenu").then((res)=>{
        data.value = res.data
  })
}
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

const TiJiaoAdd = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        role1.menus=JSON.stringify(treeRef.value.getCheckedNodes(false, false))
        console.log(role1)
        tijiao(role1)
    } else {
      console.log('error submit!', fields)
    }
  })
}
const tijiao = (role)=>{
  http.post("/LinkRoleGl/AddRole",role).then((res)=>{
      if (res.data>0){
        dialogFormVisible.value = false
        role1.roleName = ""
        role1.menus = ""
        role1.status =''
        role1.roleSort=1
        role1.remark=''
        role1.roleKey=''
        ElMessage({
          message:res.msg,
          type: 'success',
        })
        select(page.value,size.value)
      }else {
        ElMessage({
          message:res.msg,
          type: 'error',
        })
      }
  })
}

const rules = ({
  roleName:[
    {required:true,message:"角色名不能为空",trigger:'blur'},
  ],
  roleKey:[
    {required:true,message:"权限字符不能为空",trigger:'blur'}
  ],
  status: [
    {required: true, message: 'Please select activity resource', trigger: 'change'}
  ],
  remark: [
    { required: true, message: 'Please input activity form', trigger: 'blur' },
  ]
})

const Upd1 = ()=>{
  title.value = "修改角色"
  Object.assign(role1,multipleSelection.value[0])
  selectMenuRole(role1.roleId)
  dialogFormVisible.value  = true
}
const selectMenuRole = (id)=>{
   http.post("/LinkRoleGl/selectMenuRole",{id:id}).then((res)=>{
     if (res.data.length == 0){
       treeRef.value.setCheckedKeys([], false)
     }else {
       res.data.forEach(function (item,index){
         dataHx.value[index] = item.menuId
       })
       treeRef.value.setCheckedKeys(dataHx.value, false)
     }
   })
}

//批量删除
const DelRoleMany = () =>{
  if (multipleSelection.value.length>0){
    const roleids = ref([])
    multipleSelection.value.forEach(function (item,index){
       roleids.value[index] = item.roleId
    })
    del(roleids.value)
  }else {
    ElMessage({
      message: '没有选择要删除的角色,请选择一个或多个角色',
      type: 'warning',
    })
  }
}

//单个删除
const DelRole=(scop)=>{
    del(scop.roleId)
}
//删除axios
const del = (ids)=>{
  console.log(ids)
  http.post("/LinkRoleGl/DeleteRole",{ids:ids}).then((res)=>{
       if (res.data>0){
         ElMessage({
           type:"success",
           message:res.msg
         })
         select(page.value,size.value)
       }else {
         ElMessage({
           type:"error",
           message:res.msg
         })
       }
  })
}

</script>

<template>
  <div>
    <!--   导航区   -->
    <div class="Rolea1" >
      <el-icon size="23" @click="aa"><Fold /></el-icon>
      <div style="display: inline-block;margin-left: 10px;position: absolute;margin-top: 7px">
        <el-icon size="18" color="dodgerblue"><HomeFilled /></el-icon>
      </div>
      <div style="display: inline-block;margin-bottom: 5px;margin-left: 30px;margin-top: 10px">
        <el-breadcrumb separator="/" >
          <el-breadcrumb-item></el-breadcrumb-item>
          <el-breadcrumb-item>   <span style="font-size: 13px;color: black">系统管理</span> </el-breadcrumb-item>
          <el-breadcrumb-item>   <span style="font-size: 12px;color: gray">角色管理</span>   </el-breadcrumb-item>
        </el-breadcrumb>
      </div>

    </div>

    <div class="Rolea2">
      <div style="margin-top: 40px">
        <div style="display: inline-block;margin-left: 40px">
          <span style="font-size:14px;margin-right: 10px;">角色名称</span>
          <el-input v-model="role.roleName" style="width: 240px" placeholder="请输入角色名称"  />
        </div>

        <div style="display: inline-block;margin-left: 50px">
          <span style="font-size:14px;margin-right: 10px">权限字符</span>
          <el-input v-model="role.roleKey"  style="width: 240px;height: 30px"  placeholder="请输入权限字符"  />
        </div>

        <div style="display: inline-block;margin-left: 50px">
            <span style="font-size:14px;margin-right: 10px">状 态</span>
            <el-input v-model="role.status"  style="width: 240px" placeholder="请输入角色状态"  />
        </div>

        <div style="display:inline-block;margin-left: 40px;margin-top: 30px">
          <span style="font-size:14px;margin-right: 10px">创建时间</span>
          <el-date-picker v-model="role.createTime"
                          type="datetime"
              placeholder="请输入创建时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width:240px"
          />
        </div>

        <div style="display: inline-block;margin-left: 50px;margin-top: 30px">
          <el-button type="success" :icon="Search" @click="Moh">搜 索</el-button>
          <el-button type="info" :icon="Refresh" @click="ChoZ">重 置</el-button>
        </div>


      </div>

      <div style="margin-left: 40px;margin-top: 30px" >
        <el-button type="primary" :icon="Plus" @click="AddDilag" plain>新增</el-button>
        <el-button type="warning" :icon="EditPen" @click="UpdateRole" plain>修改</el-button>
        <el-button type="danger" :icon="Delete" @click="DelRoleMany" plain>删除</el-button>
        <el-button color="#626aef" :icon="Download" @click="DaoChu">导出</el-button>
      </div>

      <div style="width: 95%;margin-top: 30px;margin-left: 40px">
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="角色编号" property="roleId" width="100"  align="center"/>
          <el-table-column label="角色名称" property="roleName" width="150"  align="center"/>
          <el-table-column label="权限字符" property="roleKey" width="180" align="center" />
          <el-table-column label="显示顺序" property="roleSort" align="center" width="100"/>
          <el-table-column label="状态" property="status" width="120"  align="center">
            <template #default="scope">
              <el-switch disabled="true" v-model="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" property="createTime" width="220"  align="center"/>
          <el-table-column label="操作"  width="350"  align="center">
            <template #default="scope">
              <el-button type="primary" :icon="EditPen" @click="UpdAlag(scope.row)" link>修改 </el-button>
              <el-button type="primary" :icon="CircleCheck" link>数据权限 </el-button>
              <el-button type="primary" :icon="Delete" @click="DelRole(scope.row)" link>删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="margin-top: 20px;margin-left: 400px">
        <PageComponent :page="page" :size="size" :total="total" @select="select"></PageComponent>
      </div>
    </div>

    <el-dialog v-model="dialogFormVisible" :title="title" width="520">
      <el-form ref="roles" :model="role1" :rules="rules" style="margin-left: 40px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="role1.roleName" autocomplete="off" style="width: 320px" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="role1.roleKey" autocomplete="off" style="width: 320px" />
        </el-form-item>
        <el-form-item label="角色顺序" style="margin-left: 10px" >
          <el-input-number v-model="role1.roleSort" :min="1" :max="10" controls-position="right" @change="handleChange"/>
        </el-form-item>

        <el-form-item label="状 态" style="margin-left: 20px" prop="status">
          <el-radio-group v-model="role1.status" class="ml-4">
            <el-radio :value="true">启 用</el-radio>
            <el-radio :value="false">禁 用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="菜单权限">
          <el-tree
              ref="treeRef"
              style="max-width: 600px"
              :data="data"
              show-checkbox
              :default-expand-all="false"
              node-key="menuId"
              highlight-current
              :props="defaultProps"
          />
        </el-form-item>

        <el-form-item label="备注" style="margin-left: 20px" prop="remark">
          <el-input v-model="role1.remark" type="textarea" style="width:320px"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm(roles)">重 置</el-button>
          <el-button type="primary" @click="TiJiaoAdd(roles)">
             提 交
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>

</template>

<style scoped lang="scss">
.Rolea1{
  width: 100%;
  height: 50px;
}
.Rolea2{
  width: 100%;
  height: 1000px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}


</style>